package com.jay.media.music.core.util

import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.ParcelFileDescriptor
import com.jay.media.music.core.R
import java.io.FileDescriptor
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream

/**
 * @author xuzhou4
 * @date 2022/3/22
 */
object AlbumUtils {

    private val sArtworkUri = Uri.parse("content://media/external/audio/albumart")
    private val sBitmapOptions: BitmapFactory.Options = BitmapFactory.Options()
    private var mCachedBit: Bitmap? = null

    fun getAlbumArt(context: Context, albumId: Long): String? {
        val mUriAlbums = "content://media/external/audio/albums"
        val projection = arrayOf("album_art")
        val cur = context.contentResolver.query(
            Uri.parse("$mUriAlbums/$albumId"),
            projection,
            null,
            null,
            null
        )

        var albumArt: String? = null
        cur?.let {
            if (it.count > 0 && it.columnCount > 0) {
                it.moveToNext()
                albumArt = it.getString(0)
            }
        }
        cur?.close()
        return albumArt
    }


    fun getArtwork(
        context: Context, song_id: Long, album_id: Long,
        allowDefault: Boolean
    ): Bitmap? {
        if (album_id < 0) {
            // This is something that is not in the database, so get the album art directly
            // from the file.
            if (song_id >= 0) {
                val bm: Bitmap? = getArtworkFromFile(context, song_id, -1)
                if (bm != null) {
                    return bm
                }
            }
            return if (allowDefault) {
                getDefaultArtwork(context)
            } else null
        }
        val res: ContentResolver = context.contentResolver
        val uri: Uri = ContentUris.withAppendedId(sArtworkUri, album_id)
        var `in`: InputStream? = null
        return try {
            `in` = res.openInputStream(uri)
            BitmapFactory.decodeStream(`in`, null, sBitmapOptions)
        } catch (ex: FileNotFoundException) {
            // The album art thumbnail does not actually exist. Maybe the user deleted it, or
            // maybe it never existed to begin with.
            var bm: Bitmap? = getArtworkFromFile(context, song_id, album_id)
            if (bm != null) {
                if (bm.config == null) {
                    bm = bm.copy(Bitmap.Config.RGB_565, false)
                    if (bm == null && allowDefault) {
                        return getDefaultArtwork(context)
                    }
                }
            } else if (allowDefault) {
                bm = getDefaultArtwork(context)
            }
            bm
        } finally {
            try {
                `in`?.close()
            } catch (ex: IOException) {
            }
        }
        return null
    }

    private fun getArtworkFromFile(context: Context, songId: Long, albumId: Long): Bitmap? {
        var bm: Bitmap? = null
        require(!(albumId < 0 && songId < 0)) { "Must specify an album or a song id" }
        try {
            if (albumId < 0) {
                val uri = Uri.parse("content://media/external/audio/media/$songId/albumart")
                val pfd: ParcelFileDescriptor? =
                    context.contentResolver.openFileDescriptor(uri, "r")
                if (pfd != null) {
                    val fd: FileDescriptor = pfd.fileDescriptor
                    bm = BitmapFactory.decodeFileDescriptor(fd)
                }
            } else {
                val uri: Uri = ContentUris.withAppendedId(sArtworkUri, albumId)
                val pfd: ParcelFileDescriptor? =
                    context.contentResolver.openFileDescriptor(uri, "r")
                if (pfd != null) {
                    val fd: FileDescriptor = pfd.fileDescriptor
                    bm = BitmapFactory.decodeFileDescriptor(fd)
                }
            }
        } catch (ex: FileNotFoundException) {
        }
        if (bm != null) {
            mCachedBit = bm
        }
        return bm
    }

    private fun getDefaultArtwork(context: Context): Bitmap? {
        val opts: BitmapFactory.Options = BitmapFactory.Options()
        opts.inPreferredConfig = Bitmap.Config.RGB_565
        return BitmapFactory.decodeResource(context.resources, R.drawable.music, opts)
    }
}